from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from .models import Notification
from .serializers import NotificationSerializer


class NotificationViewSet(viewsets.ModelViewSet):
    """
    通知视图集
    """
    serializer_class = NotificationSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        qs = Notification.objects.filter(user=self.request.user)
        is_read = self.request.query_params.get('is_read')
        if is_read in ('true', 'True', '1'):
            qs = qs.filter(read=True)
        elif is_read in ('false', 'False', '0'):
            qs = qs.filter(read=False)
        n_type = self.request.query_params.get('type')
        if n_type:
            qs = qs.filter(type=n_type)
        date_from = self.request.query_params.get('date_from')
        date_to = self.request.query_params.get('date_to')
        if date_from:
            qs = qs.filter(created_at__date__gte=date_from)
        if date_to:
            qs = qs.filter(created_at__date__lte=date_to)
        ordering = self.request.query_params.get('ordering')
        allowed = {'created_at', '-created_at'}
        if ordering in allowed:
            qs = qs.order_by(ordering)
        return qs

    def perform_create(self, serializer):
        """
        为当前用户创建通知
        """
        serializer.save(user=self.request.user)

    @action(detail=True, methods=['post'])
    def mark_read(self, request, pk=None):
        """
        标记单条通知为已读
        """
        notification = self.get_object()
        notification.read = True
        notification.save(update_fields=['read'])
        return Response({'status': 'ok'})

    @action(detail=False, methods=['post'])
    def mark_all_read(self, request):
        """
        标记当前用户所有通知为已读
        """
        qs = self.get_queryset().filter(read=False)
        qs.update(read=True)
        return Response({'status': 'ok'})

    @action(detail=False, methods=['post'])
    def clear(self, request):
        Notification.objects.filter(user=request.user).delete()
        return Response({'status': 'ok'})